<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>权限列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card class="box-card">
      <el-alert title="消息提示的文案" type="info" :closable="false" show-icon center></el-alert>
        <el-steps finish-status="success" align-center :active="activeName - 0">
          <el-step title="基本信息">
          </el-step>
          <el-step title="商品参数"></el-step>
          <el-step title="商品属性"></el-step>
          <el-step title="商品图片"></el-step>
          <el-step title="商品内容"></el-step>
          <el-step title="完成"></el-step>
        </el-steps>

      <el-form :model="goodsForm" label-position="top" ref="goodsFormRef" :rules="goodsFormRules">
        <el-tabs @tab-click="tabsClick" tab-position="left" v-model="activeName" :before-leave="beforLeave">
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="goodsForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="goodsForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="goodsForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="goodsForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_number">
              <el-cascader v-model="goodsForm.goods_cat" :options="cates" :props="cascaderProps"></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item v-for="item in manyData" :key="item.attr_id" :label="item.attr_name">
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox border v-for="(checkbixItem,index) in item.attr_vals" :key="index" :label="checkbixItem">
                </el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item v-for="item in onlyData" :key="item.attr_id" :label="item.attr_name">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              class="upload-demo"
              action="https://www.liulongbin.top:8888/api/private/v1/upload"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :headers="uploadHeaders"
              :on-success="uploadSuccess"
              list-type="picture">
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <quill-editor></quill-editor>
            <el-button type="primary" @click="addGoods" class="addBtn">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <el-dialog title="提示" :visible.sync="urlDialogVisible" width="50%">
      <img :src="imgURL" style="width:100%">
      <span slot="footer" class="dialog-footer">
        <el-button @click="urlDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="urlDialogVisible = false">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import _ from 'lodash'
export default {
  data () {
    return {
      activeName: '0',
      goodsForm: {
        goods_name: '1',
        goods_price: 1,
        goods_weight: 1,
        goods_number: '1',
        goods_cat: [2273, 2274, 2275],
        pics: []
      },
      cates: [],
      goodsFormRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' },
          { min: 1, max: 99, message: '长度在 1 到 99 个字符', trigger: 'blur' }
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' },
          { min: 1, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' },
          { min: 1, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' },
          { min: 1, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ]
      },
      cascaderValue: [],
      cascaderProps: {
        label: 'cat_name',
        expandTrigger: 'hover',
        value: 'cat_id'
      },
      manyData: [],
      onlyData: [],
      uploadHeaders: {
        Authorization: sessionStorage.getItem('token')
      },
      urlDialogVisible: false,
      imgURL: ''
    }
  },

  created () {
    this.getGoodsCate()
  },

  computed: {
    cateId () {
      if (this.goodsForm.goods_cat.length === 3) {
        return this.goodsForm.goods_cat[2]
      }
      return null
    }
  },

  methods: {
    async getGoodsCate () {
      const { data: res } = await this.$axios.get('categories')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.cates = res.data
    },
    beforLeave (activeName, oldActiveName) {
      if (oldActiveName === '0') {
        if (this.goodsForm.goods_cat.length !== 3) {
          this.$message.error('请选择三级商品分类')
          return false
        }
      }
    },
    async tabsClick () {
      if (this.activeName === '1') {
        const { data: res } = await this.$axios.get(`categories/${this.cateId}/attributes`, {
          params: {
            sel: 'many'
          }
        })
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals === '' ? [] : item.attr_vals.split(' ')
        })
        this.manyData = res.data
      } else if (this.activeName === '2') {
        const { data: res } = await this.$axios.get(`categories/${this.cateId}/attributes`, {
          params: {
            sel: 'only'
          }
        })
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.onlyData = res.data
      }
    },
    handlePreview (file) {
      this.urlDialogVisible = true
      this.imgURL = file.response.data.url
    },
    handleRemove (file) {
      const filePath = file.response.data.tmp_path
      const index = this.goodsForm.pics.findIndex(item => {
        return item.pic === filePath
      })
      this.goodsForm.pics.splice(index, 1)
    },
    uploadSuccess (res) {
      this.goodsForm.pics.push(
        { pic: res.data.tmp_path }
      )
    },
    addGoods () {
      this.$refs.goodsFormRef.validate(async flag => {
        if (!flag) return this.$message.error('请完善基本信息')
        const goodsForm = _.cloneDeep(this.goodsForm)
        goodsForm.goods_cat = goodsForm.goods_cat.join(',')
        goodsForm.attrs = []
        this.manyData.forEach(item => {
          this.goodsForm.attrs.push({
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(' ')
          })
        })
        this.onlyData.forEach(item => {
          this.goodsForm.attrs.push({
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          })
        })
        const { data: res } = await this.$axios.post('goods', goodsForm)
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.$router.push('/goods')
      })
    }
  }
}
</script>

<style scoped lang='less'>
  .el-checkbox{
    margin: 0px 5px 0px 0px;
  }

  .addBtn {
    margin-top: 10px;
  }
</style>
